import Layout from './Layout'
import { useEffect, useState } from 'react'
import { getCart } from '../../helpers/cart'
import {Row, Col,Form, Input,  Typography} from 'antd'
import CartItem from './CartItem'
import PayButton from './PayButton'

const { Title } = Typography

function Cart() {
  const [cart, setCart] = useState([])
  const [address,setAddress] = useState('')
  const [totalPrice,setTotalPrice] = useState(0)
  useEffect(() => {
    setCart(getCart())
  }, [setCart])

  useEffect(()=>{
    let totalPrice = cart.reduce((curVal,nextVal)=>{
      return curVal += nextVal.count * nextVal.price
    },0).toFixed(2)
    setTotalPrice(totalPrice)
  },[cart,setTotalPrice])

  const cartTable = () => (
    <table style={{width:"100%"}}>
      <thead className="ant-table-thead">
        <tr>
          <th className="ant-table-cell">商品封面</th>
          <th className="ant-table-cell">商品名称</th>
          <th className="ant-table-cell">商品价格</th>
          <th className="ant-table-cell">商品分类</th>
          <th className="ant-table-cell">商品数量</th>
          <th className="ant-table-cell">操作</th>
        </tr>
      </thead>
      <tbody className="ant-table-tbody">
        {
          cart.map(product =>(
              <CartItem 
                key={product._id} 
                product={product} 
                setCart = {setCart}
              />
            )
          )
        }
      </tbody>
    </table>
  )
  return (
    <Layout title="购物车" subTitle="付款吧，就可带走 😄 ！ ">
      <Row gutter={16}>
        <Col span="18">
          {
            cartTable()
          }
        </Col>
        <Col span="6">
          <Form.Item label="收获地址">
            <Input placeholder="请输入收获地址" value={address} onChange={ev=>setAddress(ev.target.value)} />
          </Form.Item>
          <Title level={5}>总价：{totalPrice}</Title>
          <PayButton address={address} cart={cart} totalPrice={totalPrice} />
        </Col>
      </Row>
    </Layout>
  )
}

export default Cart